package org.example.demo.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {
    @RequestMapping("/login")
    public Boolean login(String userName, String password, HttpSession session) {
        //校验参数的合法性
        if(userName == null || password == null || userName.length() == 0 ||password.length() == 0) {
            return false;
        }
        //另一种 (有没有长度)
//        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
//            return false;
//        }

        //进行用户名和密码的校验
        if ("admin".equals(userName) && "admin".equals(password)) {
            //设置session
            session.setAttribute("userName", "admin");
            return true;
        }
        return false;
    }

  /*  @RequestMapping("/getUserInfo")
    public String getUserInfo(HttpSession session) {  //session如果没有的话会自己创建一个空的
        //从Session 获取登录用户
        String userName = (String) session.getAttribute("userName");
        return userName;
    }*/

    @RequestMapping("/getUserInfo")
    public String getUserInfo(HttpServletRequest request) {  //session如果没有的话会自己创建一个空的
        //从Session 获取登录用户
        HttpSession session = request.getSession();
        String userName = null;
        if (session != null) {
            userName = (String) session.getAttribute("userName");
        }
        return userName;
    }
}
